package com.bravo.spit.service;

import com.bravo.common.util.IdWorker;
import com.bravo.spit.repository.SpitRepository;
import com.bravo.spit.entity.Spit;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author: Yuyong
 * @create: 2019-07-24 10:41
 **/
@Service
public class SpitService {

    @Autowired
    private SpitRepository spitRepository;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 点赞
     * @param id
     */
    public void updateThumbup(String id){
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.inc("thumbup",1);
        mongoTemplate.updateFirst(query,update,"spit");

    }
    /**
     * 查询全部纪录
     * @return
     */
    public List<Spit> findAll(){
        return spitRepository.findAll();
    }

    /**
     * 根据主键查询实体
     * @param id
     * @return
     */
    public Spit findById(String id){
        return spitRepository.findById(id).orElseGet(Spit::new);
    }

    /**
     * 发布吐槽(或吐槽评论)
     * @param spit
     */
    public void add(Spit spit){

        spit.set_id(idWorker.nextId()+"");
        spit.setPublishTime(new Date());
        spit.setVisits(0);
        spit.setShare(0);
        spit.setThumbup(0);
        spit.setComment(0);
        spit.setState("1");
        if (!StringUtils.isEmpty(spit.getParentId())){
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(spit.getParentId()));
            Update update = new Update();
            update.inc("comment",1);
            mongoTemplate.updateFirst(query, update,"spit");
        }
        spitRepository.save(spit);
    }

    /**
     * 修改
     * @param spit
     */
    public void update(Spit spit){
        spitRepository.save(spit);
    }

    /**
     * 删除
     * @param id
     */
    public void deleteById(String id){
        spitRepository.deleteById(id);
    }

    /**
     * 根据上级ID查询吐槽列表
     * @param parentId
     * @param page
     * @param size
     * @return
     */
    public Page<Spit> findByParentId(String parentId,int page,int size){
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return spitRepository.findByParentId(parentId,pageRequest);
    }


}
